/*
 * BugetModifier.cpp
 *
 *  Created on: 2013-2-5
 *      Author: Dspark
 */

#include "BugetModifier.h"

BugetModifier::BugetModifier(User& u, quint32 bid):user(u),bid(bid),
pies(Qt::Horizontal,this),totalPie(100,100),bugetPie(100)
{
	initUI();
	connect( &bt_submit, SIGNAL(clicked()), this , SLOT(slt_save()) );
}

void BugetModifier::initUI()
{
	this->setWindowModality(Qt::ApplicationModal);
	this->setAttribute(Qt::WA_DeleteOnClose,true);
	lab_viewComment.setText("审批意见");
	QHBoxLayout* vc = new QHBoxLayout;
	vc->addWidget(&lab_viewComment);
	vc->addWidget(&viewComment);
	layout.addLayout(vc);

	QGroupBox *box = new QGroupBox("已支出预算");
	QVBoxLayout* row = new QVBoxLayout;
	row->addWidget(&lab_total, 0, Qt::AlignRight);
	row->addWidget(&totalPie,1);
	box->setLayout(row);
	pies.addWidget(box);

	box = new QGroupBox("预算计划详情");
	row = new QVBoxLayout;
	row->addWidget(&lab_buget, 0 ,Qt::AlignRight);
	row->addWidget(&bugetPie,1);
	box->setLayout(row);
	pies.addWidget(box);

	layout.addWidget(&pies);
	layout.addLayout(&grid);
	this->setLayout(&layout);

	loadData();

	lab_total.setText( QString("项目预算总额度:%1万元").arg(total) );
	lab_buget.setText( QString("预算额:%1万元").arg(buget) );
	totalPie.setMax(total);
	totalPie.addItem("已支出",paid);
	totalPie.addItem("拟制定",buget);

	setWindowTitle( QString("%1-预算制定").arg(projectName));

	lab_oa.setText( "OA单号" );
	bt_add.setText("添加支出项");
	bt_modify.setText("修改选中的支出项");
	bt_delete.setText("删除选中的支出项");
	grid.addWidget(&lab_oa, 0,0);
	grid.addWidget(&oa, 0 , 1);
	grid.addWidget(&bt_add, 0 , 2);
	grid.addWidget(&bt_modify, 0, 3);
	grid.addWidget(&bt_delete, 0, 4);

	tab.setEditTriggers(QAbstractItemView::NoEditTriggers);
	tab.setSelectionBehavior(QAbstractItemView::SelectRows);
	tab.setSelectionMode(QAbstractItemView::SingleSelection);
	tab.setModel(&tabModel);

	QStringList headers;
	headers << "支出类型" <<"支付金额(万元)"<<"备注";
	tabModel.setHorizontalHeaderLabels(headers);
	grid.addWidget(&tab, 1, 1, 1, 5);
	lab_totalMade.setText( QString("已制定预算额:%1万元").arg(buget) );
	grid.addWidget(&lab_totalMade, 2,3);
	lab_comment.setText("备注");
	grid.addWidget(&lab_comment, 3, 0, 1, 1);
	tab.setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Expanding);
	tab.setMinimumHeight(100);
	comment.setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum);
	comment.setMaximumHeight(50);
	grid.addWidget(&comment, 3, 1, 1, 4);
	bt_submit.setText("提交预算表");
	grid.addWidget(&bt_submit,4,2);

	connect(&bt_add, SIGNAL(clicked()), this, SLOT(slt_addItem()) );
	connect(&bt_modify, SIGNAL( clicked() ) ,this , SLOT( slt_modifyItem() ));
	connect(&bt_delete, SIGNAL(clicked()), this, SLOT(slt_deleteItem()) );
	connect(&tab, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(  slt_modifyItem() ));
}

void BugetModifier::updateLabels()
{
	lab_totalMade.setText( QString("已制定预算额:%1万元").arg(buget) );
	lab_buget.setText( QString("预算额:%1万元").arg(buget) );
	totalPie.addItem("拟制定",buget);

}

void BugetModifier::slt_deleteItem(){

	int row = tab.currentIndex().row();
	BugetItem* it = tabModel.item(row,0)->data().value<BugetItem*>();
	QString alert = it->getId()==0?"确定删除本条支出项吗？":"确定从数据库中删除本条记录吗？";
	if(QMessageBox::warning(this,"注意",alert,QMessageBox::Yes|QMessageBox::No,QMessageBox::No)!=QMessageBox::Yes)
		return;

	buget -= it->getValue();
	qreal minus = -1*it->getValue();
	bugetPie.addItem( it->getTypeName() ,  minus);

	if(it->getId()!=0)
	{
		QSqlQuery sql(Dao.getDateBase());
		sql.prepare(
			"DELETE FROM `bugetitem` WHERE id = :id"
		);
		sql.bindValue(":id",it->getId());
		if(sql.exec())
		{
			QMessageBox::information(this,"","删除成功！");
		}else{
			QMessageBox::information(this,"","删除失败！");
			qDebug()<<"删除失败！";
			qDebug()<<sql.lastQuery();
			qDebug()<<sql.lastError().text();
		}
	}

	bugetItems.removeOne(it);
	delete it;
	updateLabels();
	renderTab();
}

bool BugetModifier::isInvalid()
{
	bool invalid = false;
	QString alert;

	if(this->oa.text().trimmed() == "")
	{
		invalid = true;
		alert.append("请填写OA单号\n");
	}
	if(bugetItems.size()<1)
	{
		invalid = true;
		alert.append("请添加至少一条支出项\n");
	}

	if(invalid)
	{
		QMessageBox::critical(this,"错误",alert);
	}
	return invalid;
}

void BugetModifier::slt_save()
{
	if(isInvalid())
	{
		return;
	}
	QSqlQuery sql(Dao.getDateBase());
	sql.prepare( "UPDATE `buget` SET "
	 " `OA` = :OA,`status` = :status, `paid` = :paid, `buget` = :buget,`comment` = :comment, `maker` = :maker,`createDate` = :createDate"
	 " WHERE id = :id"
	);
	sql.bindValue(":OA", oa.text());
	sql.bindValue(":status", (int)Buget::Suspend);
	sql.bindValue(":paid", paid);
	sql.bindValue(":buget", buget);
	sql.bindValue(":comment", comment.toPlainText());
	sql.bindValue(":maker", user.getId());
	sql.bindValue(":createDate", QDate::currentDate());
	sql.bindValue(":id",bid);
	if(sql.exec())
	{
		quint32 bid = sql.lastInsertId().toUInt();

		sql.prepare( QString("INSERT INTO `bugetitem`"
						  "(`typeId`,`bugetId`,`value`,`comment`)"
								"VALUES(:tid, %1 ,:value,:comment)").arg(bid) );
		QVariantList tidlist,valuelist,commentlist;
		foreach(BugetItem* item, bugetItems)
		{
			if(item->getId()==0)
			{
				tidlist << item->getTypeId();
				valuelist << item->getValue();
				commentlist << item->getComment();
			}
			delete item;
		}
		bugetItems.clear();
		sql.bindValue(":tid",tidlist);
		sql.bindValue(":value", valuelist);
		sql.bindValue(":comment",commentlist);

		if(sql.execBatch())
		{
			QMessageBox::information(this,"","添加成功!");
			this->hide();
			emit sig_succeed();
			deleteLater();
			//this->deleteLater();
		}else{
			qDebug()<<"Insert FAIL!";
			qDebug()<<sql.lastQuery();
			qDebug()<<sql.lastError().text();
		}
	}else{
		qDebug()<<"insert Buget Fail";
	}
}


void BugetModifier::slt_itemAdded(BugetItem* item, bool conbine)
{
	if(conbine){
		bool suspend = true;
		foreach(BugetItem* i, bugetItems){
			if( i->getTypeId() == item->getTypeId())
			{
				i->setValue(i->getValue()+item->getValue());
				suspend = false;
				delete item;
				break;
			}
		}

		if(suspend){
			bugetItems.append(item);
		}

	}else{
		bugetItems.append(item);
	}
	bugetPie.addItem(item->getTypeName(),item->getValue());
	buget += item->getValue();
	updateLabels();
	renderTab();
}

void BugetModifier::slt_addItem()
{
	BugetItemDialog* dialog = new BugetItemDialog;
	connect(dialog, SIGNAL(sig_itemAdded(BugetItem*,bool)), this, SLOT(slt_itemAdded(BugetItem*,bool)) );
	dialog->show();
}


void BugetModifier::slt_itemUpdate(BugetItem* item)
{
	int row = tab.currentIndex().row();
	BugetItem* it = tabModel.item(row,0)->data().value<BugetItem*>();

	buget -= it->getValue();
	qreal minus = -1*it->getValue();
	bugetPie.addItem( it->getTypeName() ,  minus);
	bugetPie.addItem( item->getTypeName(), item->getValue() );

	buget += item->getValue();

	bugetItems.removeOne(it);
	delete it;
	bugetItems.append(item);

	updateLabels();
	renderTab();
}

void BugetModifier::slt_modifyItem()
{
	int row = tab.currentIndex().row();
	BugetItem* item = tabModel.item(row,0)->data().value<BugetItem*>();
	BugetItemDialog* dialog = new BugetItemDialog(item);
	connect( dialog, SIGNAL(sig_itemUpdate(BugetItem*)), this, SLOT(slt_itemUpdate(BugetItem*)) );
	dialog->show();
}


void BugetModifier::renderTab()
{
	tabModel.removeRows(0,tabModel.rowCount());
	foreach(BugetItem* i, bugetItems)
	{
		QList<QStandardItem*> row;
		QStandardItem* name = new QStandardItem(i->getTypeName());
		QStandardItem* value = new QStandardItem(QString("%1").arg(i->getValue()));
		QStandardItem* comment = new QStandardItem(i->getComment());
		name->setData(QVariant::fromValue(i));
		row << name << value << comment;
		tabModel.appendRow(row);
	}
}

void BugetModifier::loadData()
{
	QSqlQuery sql(Dao.getDateBase());
	sql.prepare(
	"SELECT "
	"`OA`,`status`,`buget`,`comment`,`viewComment`,"
	"`project`.`name` AS `pname`,`project`.`totalBuget`,`project`.`paid`"
	"FROM"
	"`buget` LEFT JOIN `project` ON `buget`.`pid` = `project`.`id`"
	"WHERE `buget`.`id` = :id"
	);
	sql.bindValue(":id",bid);
	if(sql.exec())
	{
		sql.next();
		QSqlRecord r = sql.record();
		oa.setText(sql.value(r.indexOf("OA")).toString());
		status = (Buget::Status)sql.value(r.indexOf("status")).toInt();
		buget = sql.value(r.indexOf("buget")).toDouble();
		comment.setText(sql.value(r.indexOf("comment")).toString());

		viewComment.setText(sql.value(r.indexOf("viewComment")).toString());
		if(status == Buget::Suspend)
		{
			viewComment.setVisible(false);
			lab_viewComment.setVisible(false);
		}else{
			viewComment.setDisabled(true);
		}

		projectName = sql.value(r.indexOf("pname")).toString();
		total = sql.value(r.indexOf("totalBuget")).toDouble();
		paid = sql.value(r.indexOf("paid")).toDouble();

		sql.prepare(
			"SELECT "
			"`bugetitem`.`id`,`bugetitem`.`typeid` as tid,`costtype`.`name` as tname,`bugetitem`.`value`, `bugetitem`.`comment`"
			"FROM `bugetitem` "
			"left join `costtype` "
			"on `bugetitem`.`typeid` = `costtype`.`id`"
			"where `bugetitem`.`bugetId` = :bid"
		);
		sql.bindValue(":bid",bid);
		if(sql.exec())
		{
			r = sql.record();
			int i_id = r.indexOf("id");
			int i_tid = r.indexOf("tid");
			int i_tname = r.indexOf("tname");
			int i_value = r.indexOf("value");
			int i_comment = r.indexOf("comment");
			while(sql.next())
			{
				BugetItem* item = new BugetItem;
				item->setId(sql.value(i_id).toUInt());
				item->setTypeId(sql.value(i_tid).toUInt());
				item->setTypeName(sql.value(i_tname).toString());
				item->setValue(sql.value(i_value).toDouble());
				item->setComment(sql.value(i_comment).toString());
				bugetItems.append(item);
				bugetPie.addItem(item->getTypeName(),item->getValue());
			}
			renderTab();
		}else{

		}

	}else{
		qDebug()<<"Get Base Project info fail";
	}

}

BugetModifier::~BugetModifier() {
	// TODO Auto-generated destructor stub
}

